import { onUnmounted, ref } from "vue";

export const useCountDown = function () {
    // 剩余时间
    const time = ref(0);

    // 存储计时器
    const counter = ref<number>();

    // 开始计时
    const start = (countdown: number) => {
        time.value = countdown;
        counter.value = setInterval(() => {
            time.value--;
            if (time.value === 0) Promise.resolve().then(() => clearInterval(counter.value));
        }, 1000) as unknown as number;
    };

    // 清除缓存
    onUnmounted(() => clearInterval(counter.value));

    return { time, start };
};